package com.example.controller;
import com.example.mapper.RoleMapper;
import com.example.model.*;
import com.example.model.dlo.*;
import com.example.service.*;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;


@RequiredArgsConstructor
@RestController
public class CompanyRestController {
    private final UserService userService;
    private LoginUser loginUser=new LoginUser();
    private final RoleMapper roleMapper;
    private final EmployeeService employeeService;
    private final BusinessService businessService;
    private final BusinessTypeService businessTypeService;
    private final DepartmentService departmentService;
    @PostMapping("/login1")
    public ApiResponse testLogin1(@Valid @RequestBody LoginRequest loginRequest,  HttpServletRequest request) {
        User user1=userService.authenticate(loginRequest.getUsername(),loginRequest.getPassword());
        if(user1!=null){
            loginUser.setId(user1.getId());
            loginUser.setUsername(user1.getUsername());
            loginUser.setPassword(user1.getPassword());
            loginUser.setEmail(user1.getEmail());
            loginUser.setEmployee(employeeService.getEmployeeById(user1.getEmployeeId()));
            loginUser.setRole(roleMapper.selectById(user1.getRoleId()));
            loginUser.setStatus(user1.getStatus());
            loginUser.setLastLogin(user1.getLastLogin());
            loginUser.setCreateTime(user1.getCreateTime());
            loginUser.setUpdateTime(user1.getUpdateTime());
            loginUser.setDepartment(departmentService.getDepartmentById(loginUser.getEmployee().getId()));
            List<Business> businessList = businessService.getTop5Businesses();
            List<CmBusiness> cmBusinessList = new ArrayList<>();
            for (Business business : businessList) {
                CmBusiness cmBusiness = new CmBusiness();
                cmBusiness.setId(business.getId());
                cmBusiness.setName(business.getName());
                cmBusiness.setType(businessTypeService.getBusinessTypeById(business.getTypeId()));
                cmBusiness.setOwner(employeeService.getEmployeeById(business.getOwnerId()));
                cmBusiness.setStartTime(business.getStartTime());
                cmBusiness.setEndTime(business.getEndTime());
                cmBusiness.setStatus(business.getStatus());
                cmBusiness.setPriority(business.getPriority());
                cmBusiness.setDescription(business.getDescription());
                cmBusiness.setCreateTime(business.getCreateTime());
                cmBusiness.setUpdateTime(business.getUpdateTime());
                cmBusinessList.add(cmBusiness);
            }
            List<Department> departmentList = departmentService.getTop5Departments();
            List<CmDepartment> cmDepartmentList = new ArrayList<>();
            for (Department department : departmentList) {
                CmDepartment cmDepartment = new CmDepartment();
                cmDepartment.setId(department.getId());
                cmDepartment.setName(department.getName());
                cmDepartment.setParent(departmentService.getDepartmentById(department.getParentId()));
                cmDepartment.setManager(employeeService.getEmployeeById(department.getManagerId()));
                cmDepartment.setCreateTime(department.getCreateTime());
                cmDepartment.setUpdateTime(department.getUpdateTime());
                cmDepartmentList.add(cmDepartment);
            }
            loginUser.setBusinessList(cmBusinessList);
            loginUser.setDepartmentList(cmDepartmentList);
            request.getSession().setAttribute("loginUser", loginUser);
            return new ApiResponse(true, "登录成功", "index", user1) ;}
        else return new ApiResponse(false, "用户名或密码错误");
    }
    @PostMapping("/api/register")
    public ResponseEntity<?> register(@RequestBody RegisterRequest registerRequest) {
        // 调用服务层处理注册逻辑
        boolean isRegistered = userService.register(registerRequest);

        if (isRegistered) {
            return ResponseEntity.ok(Map.of("success", true, "message", "注册成功"));
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Map.of("success", false, "message", "注册失败，请重试"));
        }
    }


    @GetMapping("/api/business")
    public ResponseEntity<?> getBusinessList() {
        List<Business> businessList = businessService.getBusinessList();
        List<CmBusiness> cmBusinessList = new ArrayList<>();
        for (Business business : businessList) {
            CmBusiness cmBusiness = new CmBusiness();
            cmBusiness.setId(business.getId());
            cmBusiness.setName(business.getName());
            cmBusiness.setType(businessTypeService.getBusinessTypeById(business.getTypeId()));
            cmBusiness.setOwner(employeeService.getEmployeeById(business.getOwnerId()));
            cmBusiness.setStartTime(business.getStartTime());
            cmBusiness.setEndTime(business.getEndTime());
            cmBusiness.setStatus(business.getStatus());
            cmBusiness.setPriority(business.getPriority());
            cmBusiness.setDescription(business.getDescription());
            cmBusiness.setCreateTime(business.getCreateTime());
            cmBusiness.setUpdateTime(business.getUpdateTime());
            cmBusinessList.add(cmBusiness);
        }
        return ResponseEntity.ok(cmBusinessList);
    }
    @GetMapping("/api/business/types")
    public List<BusinessType> getBusinessTypes() {
        return businessTypeService.getBusinessTypes();
    }

    @GetMapping("/api/business/managers")
    public List<Employee> getBusinessManagers() {
        return employeeService.getBusinessEmployees();
    }
    @PostMapping("/api/business/add")
    public Map<String, Object> editBusiness(@RequestBody BusinessEditRequest request) {
        System.out.println("收到业务数据：" + request);

        //Employee manager = employeeService.getEmployeeById(request.getManagerId());

        //BusinessType type = businessTypeService.getBusinessTypeById(request.getBusinessTypeId());
        Business business = new Business();
        business.setName(request.getBusinessName());
        business.setTypeId(request.getBusinessTypeId());
        business.setOwnerId(request.getManagerId());
        business.setPriority(Priority.valueOf(request.getPriority()));

        String startDateTimeStr = request.getStartDate() + "T00:00:00";
        String endDateTimeStr = request.getEndDate() + "T23:59:59";

        business.setStartTime(LocalDateTime.parse(startDateTimeStr));
        business.setEndTime(LocalDateTime.parse(endDateTimeStr));

        business.setStatus(BusinessStatus.valueOf(request.getStatus()));
        business.setDescription(request.getDescription());
        business.setCreateTime(LocalDateTime.now());
        business.setUpdateTime(LocalDateTime.now());
        businessService.insertBusiness(business);
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "业务信息已保存");
        return response;
    }

    @PutMapping("/api/business/edit/{id}")
    public Map<String, Object> updateBusiness(@PathVariable int id,@RequestBody BusinessEditRequest request) {
        System.out.println("收到业务数据：" + id+ request);
        Business business = new Business();
        business.setId(id);
        business.setName(request.getBusinessName());
        business.setTypeId(request.getBusinessTypeId());
        business.setOwnerId(request.getManagerId());
        business.setPriority(Priority.valueOf(request.getPriority()));

        String startDateTimeStr = request.getStartDate() + "T00:00:00";
        String endDateTimeStr = request.getEndDate() + "T23:59:59";

        business.setStartTime(LocalDateTime.parse(startDateTimeStr));
        business.setEndTime(LocalDateTime.parse(endDateTimeStr));

        business.setStatus(BusinessStatus.valueOf(request.getStatus()));
        business.setDescription(request.getDescription());
        business.setCreateTime(LocalDateTime.now());
        business.setUpdateTime(LocalDateTime.now());

        businessService.updateById(business); // 更新
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "业务信息已更新");
        return response;
    }

    @DeleteMapping("/api/business/delete/{id}")
    public ResponseEntity<Void> deleteBusiness(@PathVariable int id) {
        businessService.deleteBusinessById(id);
        return ResponseEntity.noContent().build();
    }
    @PostMapping("api/user/change-password")
    public ResponseEntity<?> changePassword(@RequestBody ChangePasswordRequest Passwordrequest,HttpServletRequest request) {
        loginUser = (LoginUser) request.getSession().getAttribute("loginUser");
        if (loginUser.getPassword() != Passwordrequest.getOldPassword()) {
            userService.updatePassword(loginUser.getId(), Passwordrequest.getNewPassword());
            return ResponseEntity.ok(Map.of("success", true, "message", "密码已修改"));
        } else {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Map.of("success", false, "message", "密码错误"));
        }
    }
    @GetMapping("api/department")
    public ResponseEntity<?> getDepartmentList() {
        List<Department> departmentList1 = departmentService.getDepartmentList();
        List<CmDepartment> departmentList = new ArrayList<>();
        for (Department department : departmentList1) {
            CmDepartment cmDepartment = new CmDepartment();
            cmDepartment.setId(department.getId());
            cmDepartment.setName(department.getName());
            cmDepartment.setParent(departmentService.getDepartmentById(department.getParentId()));
            cmDepartment.setManager(employeeService.getEmployeeById(department.getManagerId()));
            cmDepartment.setCreateTime(department.getCreateTime());
            cmDepartment.setUpdateTime(department.getUpdateTime());
            departmentList.add(cmDepartment);
        }
        return ResponseEntity.ok(departmentList);
    }

    @GetMapping("api/department/parents")
    public List<Department> getDepartmentParents() {
        return departmentService.getDepartments();
    }

    @GetMapping("api/department/managers")
    public List<Employee> getDepartmentManagers() {
        return employeeService.getBusinessEmployees();
    }
    @PostMapping("/api/department/add")
    public Map<String, Object> editDepartment(@RequestBody DepartmentEditRequest request) {

        Department department = new Department();
        department.setName(request.getDepartmentName());
        department.setParentId(request.getParentId());
        department.setManagerId(request.getManagerId());
        String foundationDateStr = request.getFoundationDate() + "T00:00:00";
        department.setCreateTime(LocalDateTime.parse(foundationDateStr));
        department.setUpdateTime(LocalDateTime.now());
        departmentService.insertDepartment(department);
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "部门信息已保存");
        return response;
    }

    @PutMapping("/api/department/edit/{id}")
    public Map<String, Object> updateDepartment(@PathVariable int id,@RequestBody DepartmentEditRequest request) {
        System.out.println("收到部门数据：" + id+ request);
        Department department = new Department();
        department.setId(id);
        department.setName(request.getDepartmentName());
        department.setParentId(request.getParentId());
        department.setManagerId(request.getManagerId());
        String foundationDateStr = request.getFoundationDate() + "T00:00:00";
        department.setCreateTime(LocalDateTime.parse(foundationDateStr));
        department.setUpdateTime(LocalDateTime.now());
        departmentService.updateDepartment(department);
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "部门信息已保存");
        return response;
    }

    @DeleteMapping("/api/department/delete/{id}")
    public ResponseEntity<Void> deleteDepartment(@PathVariable int id) {
        departmentService.deleteDepartmentById(id);
        return ResponseEntity.noContent().build();
    }
}
